package com.youka.bussiness.aspect;

import com.youka.bussiness.common.base.BaseException;
import com.youka.bussiness.common.bean.RestResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author cai
 */
@Slf4j
@Order(-1)
@ControllerAdvice
public class BaseExceptionHandler {


    /**
     * 用户异常
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public RestResp authenticationException(BaseException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        RestResp resp = RestResp.error(e.getCode(), e.getMessage());
        return resp;
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public RestResp handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String field = error.getField();
        String code = error.getDefaultMessage();
        String message = String.format("%s:%s", field, code);
        log.error(message);
        return RestResp.error("400", message);
    }

}
